/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import estg.dae.projecto.broker.controllers.BrokerSessionLocal;
import estg.dae.projecto.broker.data.BankDao;
import estg.dae.projecto.broker.model.Bank;
import java.io.IOException;
import java.util.Collection;
import javax.ejb.EJB;
import javax.persistence.PersistenceException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mario
 */
public class BankServlet extends HttpServlet {
    private static String VIEWS_PATH = "/WEB-INF/vistas/";
    @EJB
    private BrokerSessionLocal controller;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String actionStr = request.getParameter("action");
        String jspView = "";

        if ("edit".equalsIgnoreCase(actionStr)) {
            jspView = doEdit(request, response);
        } else if ("detail".equalsIgnoreCase(actionStr)) {
            jspView = doDetail(request, response);
        } else if ("new".equalsIgnoreCase(actionStr)) {
            jspView = doNew(request, response);
        } else if ("save".equalsIgnoreCase(actionStr)) {
            jspView = doSave(request, response);
        } else if ("update".equalsIgnoreCase(actionStr)) {
            jspView = doUpdate(request, response);
        } else if ("register".equalsIgnoreCase(actionStr)) {
            jspView = doRegister(request, response);
        } else if ("unregister".equalsIgnoreCase(actionStr)) {
            jspView = doUnregister(request, response);
        } else {
            jspView = doList(request, response);
        }
        request.setAttribute("title", "Bancos\n");

        request.getRequestDispatcher(VIEWS_PATH + jspView).include(request, response);
    }

    private String doEdit(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        request.setAttribute("action", "Editar banco");
        request.setAttribute("formMethod", "update");
        request.setAttribute("instance", controller.getBank(id));

        return "BankDetail.jsp";
    }

    private String doNew(HttpServletRequest request, HttpServletResponse response) {
        Bank bank = new Bank();

        try {
            bank.setCode(request.getParameter("code"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setName(request.getParameter("name"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setShortName(request.getParameter("shortName"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setAddress(request.getParameter("address"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setPhone(request.getParameter("phone"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setResponsibleEmail(request.getParameter("responsibleEmail"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setResponsibleName(request.getParameter("responsibleName"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setHostName(request.getParameter("hostName"));
            }
        catch(Exception err) { /* silencia a excepção */}
        try {
            bank.setHostPort(Integer.parseInt(request.getParameter("serviceLocation")));
            }
        catch(Exception err) { /* silencia a excepção */}

        request.setAttribute("action", "Novo Banco");
        request.setAttribute("formMethod", "save");

        return "BankDetail.jsp";
    }

    private String doSave(HttpServletRequest request, HttpServletResponse response) {
        try{
            Bank bank = new Bank();
            bank.setCode(request.getParameter("code"));
            bank.setName(request.getParameter("name"));
            bank.setShortName(request.getParameter("shortName"));
            bank.setAddress(request.getParameter("address"));
            bank.setPhone(request.getParameter("phone"));
            bank.setResponsibleEmail(request.getParameter("responsibleEmail"));
            bank.setResponsibleName(request.getParameter("responsibleName"));
            bank.setHostName(request.getParameter("hostName"));
            bank.setHostPort(Integer.parseInt(request.getParameter("serviceLocation")));
            controller.saveBank(bank);

            return doList(request, response);
         } catch (NumberFormatException ex) {
            request.setAttribute("formError", "Tem de indicar o código do banco.");

            return doNew(request, response);
        } catch (Exception ex) {
            request.setAttribute("formError","O código bancário já existe.");

            return doNew(request, response);
        }
    }
    private String doList(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("action", "Listagem de Bancos");
        Collection<Bank> banks = controller.getAllBanks();
        request.setAttribute("collection", banks);

        return "BanksList.jsp";
    }

    private String doUpdate(HttpServletRequest request, HttpServletResponse response) {
        try{
            long code = Integer.parseInt(request.getParameter("id"));
            Bank bank = controller.getBank(code);
            bank.setName(request.getParameter("code"));
            bank.setName(request.getParameter("name"));
            bank.setShortName(request.getParameter("shortName"));
            bank.setAddress(request.getParameter("address"));
            bank.setPhone(request.getParameter("phone"));
            bank.setResponsibleEmail(request.getParameter("responsibleEmail"));
            bank.setResponsibleName(request.getParameter("responsibleName"));
            bank.setHostName(request.getParameter("hostName"));
            bank.setHostPort(Integer.parseInt(request.getParameter("serviceLocation")));
            controller.updateBank(bank);

            return doDetail(request, response, bank);

        } catch (NumberFormatException ex) {
            request.setAttribute("formError", "Tem de indicar o código do banco.");

            return doNew(request, response);
        }catch (PersistenceException ex) {
            request.setAttribute("formError", "O código bancário já existe.");

            return doNew(request, response);
        }
    }

    private String doDetail(HttpServletRequest request, HttpServletResponse response) {
        int code = Integer.parseInt(request.getParameter("id"));
        Bank bank = controller.getBank(code);
        return doDetail(request, response, bank);
    }

    private String doDetail(HttpServletRequest request, HttpServletResponse response, Bank bank) {
        request.setAttribute("action", "Dados do Banco");
        request.setAttribute("formMethod", "detail");
        request.setAttribute("editable", "disabled");
        request.setAttribute("instance", bank);

        request.setAttribute("bankStatus", bank.isActive() ? "register" : "unregister");


        return "BankDetail.jsp";
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String doRegister(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        Bank bank = controller.getBank(id);
        controller.registerBank(bank);

        return doDetail(request, response, bank);
    }

    private String doUnregister(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        Bank bank = controller.getBank(id);
        controller.unregisterBank(bank);

        return doDetail(request, response, bank);
    }

}
